--[[

--]]
local Response = Class("com.ea.core.Response")
----local logger=logger;


function Response:init()
    if ngx.var.APP_DEBUG_LOG== "true" then        ngx.log(ngx.DEBUG, logger.formatMsg("[Response:init] start."))     end
    self.headers = ngx.header
    self._output = {}
    self._cookies = {}
    self._attrs={}
    self._eof = false
    self._debug =ngx.var.APP_DEBUG_RESP;
end

function Response:write(content)
    if self._eof then
        
            ngx.log(ngx.ERR, logger.formatMsg("response has been explicitly finished before."))
      
        return
    end
    table.insert(self._output, content)
end
--[[
@获取保存的信息
]]
function Response:getAttribute(attrName)
  if not self._attrs[attrName] then 
    return nil
  else
    return self._attrs[attrName]
  end
end

function Response:addAttribute(attrName,attrValue)
  self._attrs[attrName]=attrValue
end
function Response:setHeader(key,value)
    ngx.header[key] =value
end

function Response:responseJson(jsonContent)
    if self._eof then
       
            ngx.log(ngx.ERR, logger.formatMsg("response has been explicitly finished before."))
      
        return
    end
    ngx.header["Content-Type"]="application/json;charset=UTF-8"
  
    self._eof = true        
    ngx.header["Access-Control-Allow-Headers"]= "x-requested-with"
    ngx.header["Access-Control-Allow-Methods"]= "POST, GET"
    ngx.header["Access-Control-Allow-Origin"]= "*"
    ngx.print(jsonContent)
    self._output=jsonContent;
    self:debugReqResp();
    self._output = nil
    local ok, ret = pcall(ngx.eof)
    if not ok then
       
            ngx.log(ngx.ERR, logger.formatMsg("ngx.eof() error:" .. ret))
       
    end
    
end

function Response:responseJpeg(jsonContent)
    if self._eof then
       
            ngx.log(ngx.ERR, logger.formatMsg("response has been explicitly finished before."))
        
        return
    end
    self._eof = true    
    ngx.header["Content-Type"]="image/jpeg"
    ngx.header["Access-Control-Allow-Headers"]= "x-requested-with"
    ngx.header["Access-Control-Allow-Methods"]= "POST, GET"
    ngx.header["Access-Control-Allow-Origin"]= "*"
    ngx.print(jsonContent)
    self:debugReqResp();
    self._output = nil
    local ok, ret = pcall(ngx.eof)
    if not ok then
        
            ngx.log(ngx.ERR, logger.formatMsg("ngx.eof() error:" .. ret))
        
    end
end
function Response:responsePNG(jsonContent)
    if self._eof then
        if ngx.var.APP_DEBUG_LOG== "true" then 
            ngx.log(ngx.ERR, logger.formatMsg("response has been explicitly finished before."))
        end
        return
    end
    self._eof = true    
    ngx.header["Content-Type"]="image/png"
    ngx.header["Access-Control-Allow-Headers"]= "x-requested-with"
    ngx.header["Access-Control-Allow-Methods"]= "POST, GET"
    ngx.header["Access-Control-Allow-Origin"]= "*"
    self:debugReqResp();
    ngx.print(jsonContent)
    self:debugReqResp();
    self._output = nil
    local ok, ret = pcall(ngx.eof)
    if not ok then
        ngx.log(ngx.ERR, logger.formatMsg("ngx.eof() error:" .. ret))
    end
end

function Response:writeln(content)
    if self._eof then
       
            ngx.log(ngx.ERR, logger.formatMsg("response has been explicitly finished before."))
        
        return
    end
    table.insert(self._output, content)
    table.insert(self._output, "\r\n")
end

function Response:redirect(url, status)
    ngx.redirect(url, status)
end

function Response:set_cookie(key, value, encrypt, duration, path)
    local cookie = self:_set_cookie(key, value, encrypt, duration, path)
    self._cookies[key] = cookie
    ngx.header["Set-Cookie"] = _.values(self._cookies)
end

function Response:_set_cookie(key, value, encrypt, duration, path)
    if not value then return nil end
    if not key or key == "" or not value then
        return
    end
    if not duration or duration <= 0 then
        duration = 604800 -- 7 days, 7*24*60*60 seconds
    end
    if not path or path == "" then
        path = "/"
    end
    if value and value ~= "" and encrypt == true then
        value = ndk.set_var.set_encrypt_session(value)
        value = ndk.set_var.set_encode_base64(value)
    end
    local expiretime = ngx.time() + duration
    expiretime = ngx.cookie_time(expiretime)
    return table.concat({ key, "=", value, "; expires=", expiretime, "; path=", path })
end

function Response:error(info)
    if self._eof then
        ngx.log(ngx.ERR, logger.formatMsg("response has been explicitly finished before."))
        return
    end
    ngx.status = 500
    self.headers['Content-Type'] = 'text/html; charset=utf-8'
    self:write(info)
end


function Response:finish()
    if self._eof then
        return
    end
    self._eof = true
    ngx.header["Access-Control-Allow-Headers"]= "x-requested-with"
    ngx.header["Access-Control-Allow-Methods"]= "POST, GET"
    ngx.header["Access-Control-Allow-Origin"]= "*"
    ngx.print(self._output)
    self:debugReqResp();
    self._output = nil
    
    local ok, ret = pcall(ngx.eof)
    if not ok then
        ngx.log(ngx.ERR, logger.formatMsg("ngx.eof() error:" .. ret))
    end
end
--[[
判断当前的响应是否已经结束,如果已经结束，那么后续的逻辑将结束。
]]
function Response:isEof()
  if self._eof then return true else return false end
end

function Response:debugReqResp()
  if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg(string.format("DEBUG_RESP =%s DEBUG_REQ=%s",ngx.var.APP_DEBUG_RESP,ngx.var.APP_DEBUG_REQ))) end
  if _.isEmpty(ngx.var.APP_DEBUG_RESP)==false and ngx.var.APP_DEBUG_RESP=="true"
   then
      local h = ngx.resp.get_headers()
      for k, v in pairs(h) do
         if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg(string.format("response header %s : %s",k,v))); end
      end
      if type(self._output)=="table" and _.isEmpty(self._output)==false then
          if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg(string.format("response body :\r\n %s",unpack(self._output)))) end
      else
        if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg(string.format("response body :\r\n %s",self._output))) end
      end
  end
  
   if _.isEmpty(ngx.var.APP_DEBUG_REQ)==false and ngx.var.APP_DEBUG_REQ=="true" then
      local h = ngx.req.get_headers()
      for k, v in pairs(h) do
         if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg(string.format("request header %s : %s",k,v))); end
      end
      local last_req_args = {};    
      if _.isEmpty(ngx.req.get_uri_args())==false then
        for k,v in pairs(ngx.req.get_uri_args()) do
          last_req_args[k] = v;
         end
      end
      if ngx.req.get_method==ngx.HTTP_POST then
          ngx.req.read_body();     
          for k,v in pairs(ngx.req.get_post_args()) do
            last_req_args[k] = v;
          end 
      end
    
      if not last_req_args then
        last_req_args = {};
      end
      if ngx.var.APP_DEBUG_LOG== "true" then ngx.log(ngx.DEBUG,logger.formatMsg(string.format("request parameters :%s",cjson.encode(last_req_args)))); end     
      
     
   end

end

return Response